package top.xuwuqiang.study.webdemo.dao;

import top.xuwuqiang.study.webdemo.ebtity.TbComputer;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

public class TbComputerDAO {
    public static int insert(TbComputer tbComputer)throws SQLException{
        Connection conn=DBHelper.getConnection();
        String sql="insert into tb_computer(changshang,dnjj,price)values(?,?,?)";
        PreparedStatement ps=conn.prepareStatement(sql);

        ps.setString(1,tbComputer.getChangshang());

        ps.setString(2,tbComputer.getDnjj());
        ps.setInt(3,tbComputer.getPrice());


        int i=ps.executeUpdate();
        conn.close();

        return i;
    }
    public static List<TbComputer> query() throws SQLException {
        List<TbComputer>list=new ArrayList<>();
//        查询的语句
        Connection conn=DBHelper.getConnection();

//        查询语句
        String sql="select * from tb_computer";
//      预处理sql语句
        PreparedStatement ps=conn.prepareStatement(sql);
//        执行查询并返回结果集
        ResultSet rs= ps.executeQuery();
//查询结果集的next是读取下一行数据，读取到就返回真，没有就返回假
        while (rs.next()){
//            将数据库的记录转换为java对向
            TbComputer tbComputer=new TbComputer();
//            re.get数据类型（“数据表中字段名称”）就是获取查询结果中指定字段的数据
            tbComputer.setId(rs.getInt("id"));
            tbComputer.setChangshang(rs.getString("changshang"));
            tbComputer.setDnjj(rs.getString("dnjj"));
//            java的Date类型对应的是数据库api的Timestamp类型
            tbComputer.setPrice(rs.getInt("price"));
//            添加到集合
            list.add(tbComputer);
        }

        conn.close();
        return list;

    }

    public static  int delete(Integer id) throws SQLException {
        Connection conn=DBHelper.getConnection();
        String sql="delete from tb_computer where id=?";
        PreparedStatement ps= conn.prepareStatement(sql);
        ps.setInt(1,id);
        int i=ps.executeUpdate();
        conn.close();
        return i;



    }

}
